import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';

/**
 * @param ele 要生成 PDF 的 DOM 元素（容器）
 * @param pdfName PDF 文件的生成名字
 */
function downloadPDF(ele: HTMLElement, pdfName: string) {
    // 确保所有图片已加载
    const loadImages = Array.from(ele.querySelectorAll('img')).map((img) => {
        return new Promise<void>((resolve, reject) => {
            if (img.complete) {
                resolve();
            } else {
                img.onload = () => resolve();
                img.onerror = (error) => reject(error);
            }
        });
    });

    Promise.all(loadImages)
        .then(() => {
            const eleW = ele.offsetWidth;
            const eleH = ele.offsetHeight;

            const pdf = new jsPDF({
                unit: 'pt',
                format: [eleW, eleH],
            });

            html2canvas(ele, {
                scale: 2, // 提高分辨率
                useCORS: true, // 允许跨域
                timeout: 10000, // 增加超时时间以确保图片加载
            })
                .then((canvas: HTMLCanvasElement) => {
                    const imgData = canvas.toDataURL('image/jpeg', 1); // 高质量
                    const pdfWidth = pdf.internal.pageSize.getWidth();
                    const pdfHeight = pdf.internal.pageSize.getHeight();
                    const ratio = Math.min(
                        pdfWidth / eleW,
                        pdfHeight / eleH
                    );

                    // 添加图片到 PDF
                    pdf.addImage(imgData, 'JPEG', 0, 0, eleW * ratio, eleH * ratio);

                    // 下载 PDF
                    pdf.save(pdfName);
                })
                .catch((error) => {
                    console.error('Error creating canvas:', error);
                });
        })
        .catch((error) => {
            console.error('Error loading images:', error);
        });
}

export { downloadPDF };
